package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

type Person struct {
	ID       int    `db:"user_id"`
	UserName string `db:"username"`
	Sex      string `db:"sex"`
	Email    string `db:"email"`
}

type Place struct {
	Country string `db:"country"`
	City    string `db:"city"`
	TelCode int    `db:"telcode"`
}

var Db *sqlx.DB

func Init() {
	fmt.Println("grom连接mysql数据库操作")
	db, err := sqlx.Open("mysql", "root:8rPwHjXC7C^WCt@4@tcp(127.0.0.1:3306)/dbTest")
	if err != nil {
		fmt.Println("open mysql failed,", err)
		return
	}
	Db = db
	fmt.Println("连接接成功")

}
func InsertTest() {
	r, err := Db.Exec("insert into person(username,sex,email)values(?,?,?)", "张三", "男", "123@mail")
	if err != nil {
		fmt.Println("执行失败,", err)
		return
	}
	id, err := r.LastInsertId()
	if err != nil {
		fmt.Println("执行失败，", err)
		return
	}
	fmt.Println("插入成功", id)
}

func SelectTest() {
	var person []Person
	err := Db.Select(&person, "select *from person")
	if err != nil {
		fmt.Println("执行失败")
		return
	}
	fmt.Println("执行成功，查询为： ", person)
}

func main() {
	Init()
	//InsertTest()
	//SelectTest()
}
